package com.koomii.common.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchProviderException;
import java.util.Calendar;
import java.util.Locale;


/**
 * 订单详情url加密算法，.net负责来解密，该类是（高建峰）提供
 * USER:YINWEI
 * TIME:2010-07-20
 */
public class DES {
    private final byte[] salt = "3#6q0/bj".getBytes();

    private SecretKey deskey;

    private Cipher c;

    //private byte[] cipherByte;

    // Key key;

    /**
     * 初始化 DES 实例
     */
    public DES() {
        try {
            init("3#6q0/bj");
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        }
    }


    javax.crypto.spec.IvParameterSpec iv = new javax.crypto.spec.IvParameterSpec(
            salt);

    public void init(String strKey) throws NoSuchProviderException {
        try {
            // KeyGenerator _generator ;// = KeyGenerator.getInstance("DES");
            // java.security.Key k;
            // deskey = KeyGenerator.getInstance("DES").generateKey();
            DESKeySpec desKeySpec = new DESKeySpec(strKey.getBytes());

            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
            deskey = secretKey;
            c = Cipher.getInstance("DES/CBC/PKCS5Padding");
            c.init(Cipher.ENCRYPT_MODE, deskey, iv);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String toHexString(byte b[]) {
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            String plainText = Integer.toHexString(0xff & b[i]);
            if (plainText.length() < 2)
                plainText = "0" + plainText;
            hexString.append(plainText);
        }
        return hexString.toString();

    }

    /**
     * 对 String 进行加密
     *
     * @param str 要加密的数据
     * @return 返回加密后的 byte 数组
     * @throws java.io.UnsupportedEncodingException
     *
     */
    public byte[] createEncryptor(String str)
            throws UnsupportedEncodingException,
            InvalidAlgorithmParameterException {
        try {
            //c.init(Cipher.ENCRYPT_MODE, deskey, iv);
            return c.doFinal(str.getBytes());
            //} catch (java.security.InvalidKeyException ex) {
            //	ex.printStackTrace();
        } catch (javax.crypto.BadPaddingException ex) {
            ex.printStackTrace();
            //ex//c.
            //c.
        } catch (javax.crypto.IllegalBlockSizeException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public String encode(String wid) throws UnsupportedEncodingException, InvalidAlgorithmParameterException {
        Calendar c = Calendar.getInstance(Locale.CHINESE);
        String s = String.format("%03d", c.get(Calendar.DAY_OF_YEAR)) + wid;
        //return toHexString(createEncryptor(s)).toUpperCase();
        return toHexString(createEncryptor(s)).toUpperCase();
	}


    public static void main(String[] args){

        DES des = new DES();

        try {
            System.out.println(des.encode("venderorderinfo"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

    }

}
